/**
 *
 */
package com.leonzx.base.config.jim.command;

import cn.hutool.core.util.RandomUtil;
import com.leonzx.base.config.jim.entity.CustomUser;
import com.leonzx.base.config.jim.service.ImgMnService;
import com.leonzx.base.entity.system.Orders;
import com.leonzx.base.entity.system.Role;
import com.leonzx.base.service.system.OrdersService;
import com.leonzx.base.service.system.RoleService;
import com.leonzx.base.service.system.UserService;
import com.leonzx.base.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.ImSessionContext;
import org.jim.common.packets.Group;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.packets.User;
import org.jim.common.session.id.impl.UUIDSessionIdGenerator;
import org.jim.server.command.handler.processor.login.LoginProcessorIntf;
import org.tio.core.ChannelContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Liang
 */
public class LoginServiceProcessor implements LoginProcessorIntf {

    private UserService userService;
    private OrdersService ordersService;
    private RoleService roleService;

    public LoginServiceProcessor(UserService userService, OrdersService ordersService, RoleService roleService) {
        this.userService = userService;
        this.ordersService = ordersService;
        this.roleService = roleService;
    }

    public static final Map<String, User> tokenMap = new HashMap<>();

    private static String[] familyName = new String[]{"谭", "刘", "张", "李", "胡", "沈", "朱", "钱", "王", "伍", "赵", "孙", "吕", "马", "秦", "毛", "成", "梅", "黄", "郭", "杨", "季", "童", "习", "郑",
            "吴", "周", "蒋", "卫", "尤", "何", "魏", "章", "郎", " 唐", "汤", "苗", "孔", "鲁", "韦", "任", "袁", "贺", "狄朱"};

    private static String[] secondName = new String[]{"艺昕", "红薯", "明远", "天蓬", "三丰", "德华", "歌", "佳", "乐", "天", "燕子", "子牛", "海", "燕", "花", "娟", "冰冰", "丽娅", "大为", "无为", "渔民", "大赋",
            "明", "远平", "克弱", "亦菲", "靓颖", "富城", "岳", "先觉", "牛", "阿狗", "阿猫", "辰", "蝴蝶", "文化", "冲之", "悟空", "行者", "悟净", "悟能", "观", "音", "乐天", "耀扬", "伊健", "炅", "娜", "春花", "秋香", "春香",
            "大为", "如来", "佛祖", "科比", "罗斯", "詹姆屎", "科神", "科蜜", "库里", "卡特", "麦迪", "乔丹", "魔术师", "加索尔", "法码尔", "南斯", "伊哥", "杜兰特", "保罗", "杭州", "爱湘", "湘湘", "昕", "函", "鬼谷子", "膑", "荡",
            "子家", "德利优视", "五方会谈", "来电话了", "T-IO", "Talent", "轨迹", "超"};

    /**
     * 登陆时设置用后名称和群组
     *
     * @param loginname
     * @param number    群组
     * @return
     * @author: WChao
     */
    public User getUser(String loginname, String number) {
        CustomUser user = new CustomUser();
        //根据用户名查询数据库人员信息
        com.leonzx.base.entity.system.User currentUser = userService.getByUsername(loginname);
        user.setId(currentUser.getId());//设置人员ID
        user.setNumber(number);//群组号码
        user.setName(currentUser.getName());//设置人员名称
        user.setNick(currentUser.getName());//设置人员名称
        user.setGroups(initGroups(user));//设置群组
        user.setFriends(initFriends());//设置好友
        user.setAvatar(nextImg());//设置签名
        return user;
    }

    /**
     * 根据token获取用户信息
     *
     * @param token
     * @return
     * @author: WChao
     */
    public User getUser(String token) {
        //demo中用map，生产环境需要用cache
        CustomUser user = (CustomUser) tokenMap.get(token);
        if (user == null) {
            user = new CustomUser();
            user.setId(UUIDSessionIdGenerator.instance.sessionId(null));
            user.setNick(familyName[RandomUtil.randomInt(0, familyName.length - 1)] + secondName[RandomUtil.randomInt(0, secondName.length - 1)]);

            user.setGroups(initGroups(user));
            user.setFriends(initFriends());
            user.setAvatar(nextImg());

            if (tokenMap.size() > 10000) {
                tokenMap.clear();
            }
            tokenMap.put(token, user);
        }
        return user;
    }

    /**
     * 初始化群组
     * 1 当number有值时则默认进入该群组 PC委托单列表已用
     * 2 默认加入委托单STATE =1 群组 PC layIm 和手机已用
     *
     * @param user
     * @return
     */

    public List<Group> initGroups(CustomUser user) {
        //模拟的群组;正式根据业务去查数据库或者缓存;
        //业务是默认人员进入所有委托state=1的群组
        List<Group> groups = new ArrayList<Group>();
        Orders orders = new Orders();
        orders.setState(Constants.STATE_VAILD);
        List<Orders> ordersList = ordersService.getAllBaseOrders(orders);
        if (StringUtils.isNotBlank(user.getNumber())) {
            String id = ordersService.findIdByNumber(user.getNumber());
            groups.add(new Group(id, user.getNumber()));
        } else {
            for (Orders orders1 : ordersList) {
                groups.add(new Group(orders1.getId(), orders1.getNumber()));
            }
        }
        return groups;
    }

    /**
     * 默认公司所有人都是好友
     *
     * @return
     */
    public List<Group> initFriends() {
        List<Group> friends = new ArrayList<>();
        Role role = new Role();
        role.setState(Constants.STATE_VAILD);
        List<Role> roleList = roleService.getAllBaseRole(role);
        for (Role currentRole : roleList) {
            //1分组(没有部门 先用角色当临时组)
            List<User> myFriendGroupUsers = new ArrayList<>();
            //2人员
            List<com.leonzx.base.entity.system.User> userList = userService.findUserByRoleId(currentRole.getId());
            for (com.leonzx.base.entity.system.User user : userList) {
                User user1 = new User();
                user1.setId(user.getId());
                user1.setNick(user.getName());
                user1.setAvatar(nextImg());
                myFriendGroupUsers.add(user1);
            }
            Group myFriend = new Group(currentRole.getId(), currentRole.getName());
            myFriend.setUsers(myFriendGroupUsers);
            friends.add(myFriend);
        }
        return friends;
    }

    public String nextImg() {
        return ImgMnService.nextImg();
    }

    @Override
    public User getUser(LoginReqBody loginReqBody, ChannelContext channelContext) {
        String loginname = loginReqBody.getLoginname();
        String password = loginReqBody.getPassword();
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
/*		String handshakeToken = imSessionContext.getToken();
		if (!StringUtils.isBlank(handshakeToken)) {
			return this.getUser(handshakeToken);
		}*/
        return this.getUser(loginname, password);
    }

    @Override
    public boolean isProtocol(ChannelContext channelContext) {
        return true;
    }

    @Override
    public String name() {
        return "default";
    }
}
